package com.paishen.common.dialog;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.AnimationDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.paishen.common.R;

/**
 * Created by peng on 2015/12/4.
 */
public class LoadingDialog extends Dialog {

    public LoadingDialog(Context context, int themeResId) {
        super(context, themeResId);
    }

    public static class Builder {
        private final Context context;
        private boolean shadow = false;
        private boolean canCancel = true;
        private String message;

        public Builder(Context context) {
            this.context = context;
            message = context.getString(R.string.load);
        }

        public Builder setShadow(boolean shadow) {
            this.shadow = shadow;
            return this;
        }

        public Builder setCanCancel(boolean canCancel) {
            this.canCancel = canCancel;
            return this;
        }

        public Builder setMessage(int textId) {
            message = this.context.getString(textId);
            return this;
        }

        public Builder setMessage(String text) {
            message = text;
            return this;
        }

        public LoadingDialog create() {
            final LoadingDialog dialog = new LoadingDialog(context, shadow ? R.style.Theme_Light_NoTitle_Dialog : R.style.Theme_Light_NoTitle_NoShadow_Dialog);

            Window win = dialog.getWindow();
            WindowManager.LayoutParams lp = win.getAttributes();
            lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
            lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
            win.setAttributes(lp);

            View view = LayoutInflater.from(context).inflate(R.layout.dialog_common_loading, null);
            final ImageView imgLoading = (ImageView) view.findViewById(R.id.img_loading);
            ((AnimationDrawable) imgLoading.getBackground()).start();
            final TextView txMessage = (TextView) view.findViewById(R.id.tx_message);
            txMessage.setText(message);

            dialog.setContentView(view);
            dialog.setCanceledOnTouchOutside(canCancel);
            dialog.setCancelable(canCancel);

            dialog.setOnDismissListener(new OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    ((AnimationDrawable) imgLoading.getBackground()).stop();
                }
            });

            return dialog;
        }
    }
}
